<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="方剂名称">
          <el-input v-model="searchForm.name" placeholder="请输入方剂名称" clearable />
        </el-form-item>
        <el-form-item label="方剂分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="功效">
          <el-select v-model="searchForm.efficacy" placeholder="请选择功效" clearable>
            <el-option v-for="item in efficacyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" :icon="Plus" @click="handleAdd">添加方剂</el-button>
      <el-button type="danger" :icon="Delete" :disabled="!selectedItems.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" :icon="Upload" @click="handleImport">导入</el-button>
      <el-button type="info" :icon="Download" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="方剂名称" width="150" />
        <el-table-column prop="pinyin" label="拼音" width="120" />
        <el-table-column prop="alias" label="别名" width="150" />
        <el-table-column prop="category" label="方剂分类" width="120" />
        <el-table-column prop="efficacy" label="功效" width="150" />
        <el-table-column prop="source" label="出处" width="180" />
        <el-table-column prop="composition" label="组成" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加方剂' : '编辑方剂'"
      width="650px"
      @closed="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="方剂名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入方剂名称" />
        </el-form-item>
        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="formData.pinyin" placeholder="请输入拼音" />
        </el-form-item>
        <el-form-item label="别名" prop="alias">
          <el-input v-model="formData.alias" placeholder="请输入别名，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="方剂分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="功效" prop="efficacy">
          <el-select v-model="formData.efficacy" multiple placeholder="请选择功效" style="width: 100%">
            <el-option v-for="item in efficacyOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出处" prop="source">
          <el-input v-model="formData.source" placeholder="请输入出处" />
        </el-form-item>
        <el-form-item label="组成" prop="composition">
          <el-table :data="formData.herbs" style="width: 100%" border>
            <el-table-column label="药材" width="150">
              <template #default="scope">
                <el-select 
                  v-model="scope.row.herb" 
                  filterable 
                  placeholder="选择药材"
                  style="width: 100%"
                >
                  <el-option
                    v-for="option in herbOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="用量" width="150">
              <template #default="scope">
                <el-input v-model="scope.row.amount" placeholder="例如: 10g" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button
                  type="danger"
                  circle
                  plain
                  size="small"
                  :icon="Delete"
                  @click="removeHerb(scope.$index)"
                />
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px;">
            <el-button type="primary" plain size="small" :icon="Plus" @click="addHerb">添加药材</el-button>
          </div>
        </el-form-item>
        <el-form-item label="制法用法" prop="preparation">
          <el-input v-model="formData.preparation" type="textarea" rows="3" placeholder="请输入制法用法" />
        </el-form-item>
        <el-form-item label="功效主治" prop="indication">
          <el-input v-model="formData.indication" type="textarea" rows="3" placeholder="请输入功效主治" />
        </el-form-item>
        <el-form-item label="加减化裁" prop="modification">
          <el-input v-model="formData.modification" type="textarea" rows="3" placeholder="请输入加减化裁" />
        </el-form-item>
        <el-form-item label="注意事项" prop="precautions">
          <el-input v-model="formData.precautions" type="textarea" rows="3" placeholder="请输入注意事项" />
        </el-form-item>
        <el-form-item label="临床应用" prop="clinical">
          <el-input v-model="formData.clinical" type="textarea" rows="3" placeholder="请输入临床应用" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="方剂详情"
      width="700px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="方剂名称">{{ detailData.name }}</el-descriptions-item>
        <el-descriptions-item label="拼音">{{ detailData.pinyin }}</el-descriptions-item>
        <el-descriptions-item label="别名">{{ detailData.alias }}</el-descriptions-item>
        <el-descriptions-item label="方剂分类">{{ detailData.category }}</el-descriptions-item>
        <el-descriptions-item label="功效">{{ Array.isArray(detailData.efficacy) ? detailData.efficacy.join('、') : detailData.efficacy }}</el-descriptions-item>
        <el-descriptions-item label="出处">{{ detailData.source }}</el-descriptions-item>
        <el-descriptions-item label="组成" :span="2">
          <el-table :data="detailData.herbsArray || []" border style="width: 100%">
            <el-table-column prop="herb" label="药材" width="180" />
            <el-table-column prop="amount" label="用量" width="120" />
          </el-table>
        </el-descriptions-item>
        <el-descriptions-item label="制法用法" :span="2">{{ detailData.preparation }}</el-descriptions-item>
        <el-descriptions-item label="功效主治" :span="2">{{ detailData.indication }}</el-descriptions-item>
        <el-descriptions-item label="加减化裁" :span="2">{{ detailData.modification }}</el-descriptions-item>
        <el-descriptions-item label="注意事项" :span="2">{{ detailData.precautions }}</el-descriptions-item>
        <el-descriptions-item label="临床应用" :span="2">{{ detailData.clinical }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入方剂数据"
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleImportFileChange"
      >
        <el-icon class="el-icon--upload"><Upload /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传xlsx或csv格式的文件，<el-button link type="primary" @click="downloadTemplate">下载模板</el-button>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImport">确定导入</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Search, Refresh, Plus, Delete, Upload, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRecipeList, getRecipeDetail, addRecipe, updateRecipe, deleteRecipe, updateRecipeStatus } from '@/api/knowledge'

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedItems = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  category: '',
  efficacy: ''
})

// 对话框显示控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const importDialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'

// 表单数据
const formRef = ref(null)
const formData = reactive({
  id: undefined,
  name: '',
  pinyin: '',
  alias: '',
  category: '',
  efficacy: [],
  source: '',
  herbs: [{ herb: '', amount: '' }],
  preparation: '',
  indication: '',
  modification: '',
  precautions: '',
  clinical: ''
})

// 详情数据
const detailData = ref({})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入方剂名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择方剂分类', trigger: 'change' }
  ],
  efficacy: [
    { required: true, message: '请选择功效', trigger: 'change' }
  ]
}

// 分类选项
const categoryOptions = [
  { value: '汤', label: '汤类' },
  { value: '粥', label: '粥类' },
  { value: '茶', label: '茶类' },
  { value: '酒', label: '酒类' },
  { value: '其他', label: '其他' }
]

// 功效选项
const efficacyOptions = [
  { value: '补气', label: '补气' },
  { value: '补血', label: '补血' },
  { value: '健脾', label: '健脾' },
  { value: '养肝', label: '养肝' },
  { value: '益肺', label: '益肺' },
  { value: '滋肾', label: '滋肾' },
  { value: '清热', label: '清热' },
  { value: '祛湿', label: '祛湿' },
  { value: '明目', label: '明目' },
  { value: '安神', label: '安神' },
  { value: '温阳', label: '温阳' }
]

// 药材选项
const herbOptions = [
  { value: '黄芪', label: '黄芪' },
  { value: '当归', label: '当归' },
  { value: '党参', label: '党参' },
  { value: '白术', label: '白术' },
  { value: '茯苓', label: '茯苓' },
  { value: '陈皮', label: '陈皮' },
  { value: '甘草', label: '甘草' },
  { value: '枸杞', label: '枸杞' },
  { value: '山药', label: '山药' },
  { value: '红枣', label: '红枣' },
  { value: '熟地黄', label: '熟地黄' },
  { value: '桂圆肉', label: '桂圆肉' },
  { value: '菊花', label: '菊花' },
  { value: '生姜', label: '生姜' }
]

// 生命周期钩子
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  getRecipeList({
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    name: searchForm.name,
    category: searchForm.category,
    efficacy: searchForm.efficacy
  }).then(response => {
    tableData.value = response.data.rows
    total.value = response.data.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 搜索操作
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.category = ''
  searchForm.efficacy = ''
  handleSearch()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 添加方剂
const handleAdd = () => {
  resetForm()
  dialogType.value = 'add'
  dialogVisible.value = true
}

// 编辑方剂
const handleEdit = (row) => {
  loading.value = true
  getRecipeDetail(row.id).then(response => {
    const data = response.data
    formData.id = data.id
    formData.name = data.name
    formData.pinyin = data.pinyin || ''
    formData.alias = data.alias || ''
    formData.category = data.category
    formData.efficacy = data.effects || []
    formData.source = data.source || ''
    
    // 转换药材列表
    if (data.ingredientList && data.ingredientList.length > 0) {
      formData.herbs = data.ingredientList.map(item => ({
        herb: item.ingredient,
        amount: `${item.amount}${item.unit}`
      }))
    } else {
      formData.herbs = [{ herb: '', amount: '' }]
    }
    
    formData.preparation = data.method || ''
    formData.indication = data.description || ''
    formData.modification = data.modification || ''
    formData.precautions = data.precautions || ''
    formData.clinical = data.clinical || ''
    
    dialogType.value = 'edit'
    dialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 查看详情
const handleView = (row) => {
  loading.value = true
  getRecipeDetail(row.id).then(response => {
    detailData.value = response.data
    
    // 转换药材列表为表格数据
    if (detailData.value.ingredientList && detailData.value.ingredientList.length > 0) {
      detailData.value.herbsArray = detailData.value.ingredientList.map(item => ({
        herb: item.ingredient,
        amount: `${item.amount}${item.unit}`
      }))
    } else {
      detailData.value.herbsArray = []
    }
    
    viewDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 删除方剂
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除方剂 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    deleteRecipe(row.id).then(response => {
      ElMessage.success('删除成功')
      fetchData()
    }).catch(() => {
      loading.value = false
    })
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确定删除选中的 ${selectedItems.value.length} 条记录吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    const ids = selectedItems.value.map(item => item.id)
    // 批量删除现在按顺序逐一删除
    Promise.all(ids.map(id => deleteRecipe(id)))
      .then(() => {
        ElMessage.success('批量删除成功')
        fetchData()
      })
      .catch(() => {
        loading.value = false
      })
  }).catch(() => {})
}

// 添加药材行
const addHerb = () => {
  formData.herbs.push({ herb: '', amount: '' })
}

// 移除药材行
const removeHerb = (index) => {
  formData.herbs.splice(index, 1)
  if (formData.herbs.length === 0) {
    formData.herbs.push({ herb: '', amount: '' })
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  formData.id = undefined
  formData.name = ''
  formData.pinyin = ''
  formData.alias = ''
  formData.category = ''
  formData.efficacy = []
  formData.source = ''
  formData.herbs = [{ herb: '', amount: '' }]
  formData.preparation = ''
  formData.indication = ''
  formData.modification = ''
  formData.precautions = ''
  formData.clinical = ''
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      // 过滤掉空的药材
      const validHerbs = formData.herbs.filter(h => h.herb && h.amount)
      
      // 构建API所需数据格式
      const submitData = {
        id: formData.id,
        name: formData.name,
        pinyin: formData.pinyin,
        alias: formData.alias,
        category: formData.category,
        effects: formData.efficacy,
        source: formData.source,
        // 转换药材格式
        ingredientList: validHerbs.map(h => {
          // 从"10g"中提取数量和单位
          const match = h.amount.match(/^(\d+(?:\.\d+)?)(.*)$/)
          return {
            ingredient: h.herb,
            amount: match ? parseFloat(match[1]) : 0,
            unit: match ? match[2] || '克' : '克'
          }
        }),
        method: formData.preparation,
        description: formData.indication,
        modification: formData.modification,
        precautions: formData.precautions,
        clinical: formData.clinical,
        status: 1 // 默认启用
      }
      
      if (dialogType.value === 'edit') {
        updateRecipe(submitData).then(response => {
          ElMessage.success('修改成功')
          dialogVisible.value = false
          fetchData()
        }).catch(() => {
          loading.value = false
        })
      } else {
        addRecipe(submitData).then(response => {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          fetchData()
        }).catch(() => {
          loading.value = false
        })
      }
    }
  })
}

// 导入相关
const handleImport = () => {
  importDialogVisible.value = true
}

const handleImportFileChange = (file) => {
  // 处理文件变化
  console.log('选择了文件:', file)
}

const confirmImport = () => {
  ElMessage.success('导入功能开发中')
  importDialogVisible.value = false
}

const downloadTemplate = () => {
  // 下载模板
  ElMessage.info('模板下载功能开发中')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchData()
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .action-container {
    margin-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    gap: 10px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 